package org.yxj.requestlib.manager.api;


import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.logging.HttpLoggingInterceptor;

public class MyHttpLoggingInterceptor{

    public static final String TAG = "MyHttpLoggingInterceptor";

    public MyHttpLoggingInterceptor(){
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    }

    public HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            // Android json数据Log格式化打印
            printJson(TAG,message);
            // 打印retrofit日志
            Log.i("RetrofitLog","retrofitBack = "+message);
        }
    });


    public void printJson(String tag, String msg) {
        String message;
        try {
            if (msg.startsWith("{")) {
                JSONObject jsonObject = new JSONObject(msg);
                //最重要的方法，就一行，返回格式化的json字符串，其中的数字4是缩进字符数
                message = jsonObject.toString(4);
            } else if (msg.startsWith("[")) {
                JSONArray jsonArray = new JSONArray(msg);
                message = jsonArray.toString(4);
            } else {
                message = msg;
            }
        } catch (JSONException e) {
            message = msg;
        }
        Log.d(tag, message);
    }
}
